# -*- coding: utf-8 -*-
import re
import minidom as dom

from urlparse import urljoin, urlunparse

def smart_base(local, local_base, url_base, skin=None):
    base = ''
    if local:
        base = urlunparse(('file', '', local_base, '', '', False))
    else:
        base = url_base.rstrip('/')+'/'
    if not skin is None:
        base = urljoin(base, skin).rstrip('/')+'/'
    return base

def extract_stylesheet(doc):
    """
    From parsed document extracts processing instruction's href
    Requires a DOM-compliant tree as input.
    """
    href = ''
    pi = ''
    for child in doc.childNodes:
        if child.nodeType == child.PROCESSING_INSTRUCTION_NODE and child.nodeName == 'xml-stylesheet':
            pi = child
        break
    if(pi): href = re.search('href=[\'\"](.*)[\'\"]', pi.data).group(1)
    return (pi, href)
